package j2src;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import javax.naming.NamingException;
import javax.naming.Context;
import javax.ejb.EJBHome;
import javax.ejb.EJBLocalHome;

import java.util.Properties;


public class WhiteDaoLocator {
	
	
	private static WhiteDaoLocator whiteDaoLocator;
	private static Context context;
	protected WhiteDaoLocator() throws WhiteDaoLocatorException {
		try {
			context = getInitialContext();
		} catch (Exception e) {
			throw new WhiteDaoLocatorException(e.getMessage());
		}
	}
	
	public static EJBHome getEjbHome(String ejbName, Class ejbClass) throws
	WhiteDaoLocatorException {
		try {
			Object object = context.lookup(ejbName);
			EJBHome ejbHome = null;
			ejbHome = (EJBHome) PortableRemoteObject.narrow(object, ejbClass);
			if (ejbHome == null) {
				throw new WhiteDaoLocatorException("Could not get home for " +
						ejbName);
			}
			return ejbHome;
		} catch (NamingException ne) {
			throw new WhiteDaoLocatorException(ne.getMessage());
		}
	}
	
	public static EJBLocalHome getEjbLocalHome(String ejbName) throws
	WhiteDaoLocatorException {
		try {
			Context localContext = new InitialContext();
			Object object = localContext.lookup(ejbName);
			EJBLocalHome ejbLocalHome = null;
			ejbLocalHome = (EJBLocalHome) object;
			if (ejbLocalHome == null) {
				throw new WhiteDaoLocatorException(
						"Could not get local home for " + ejbName);
			}
			return ejbLocalHome;
		} catch (NamingException ne) {
			throw new WhiteDaoLocatorException(ne.getMessage());
		}
	}
	
	public static synchronized WhiteDaoLocator getInstance() throws
	WhiteDaoLocatorException {
		if (whiteDaoLocator == null) {
			whiteDaoLocator = new WhiteDaoLocator();
		}
		return whiteDaoLocator;
	}
	
	public Context getInitialContext() throws Exception {
		String url = "t3://localhost:7001";
		String user = null;
		String password = null;
		Properties properties;
		try {
			properties = new Properties();
			properties.put(Context.INITIAL_CONTEXT_FACTORY,
			"weblogic.jndi.WLInitialContextFactory");
			properties.put(Context.PROVIDER_URL, url);
			if (user != null) {
				properties.put(Context.SECURITY_PRINCIPAL, user);
				properties.put(Context.SECURITY_CREDENTIALS,
						password == null ? "" : password);
			}
			return new javax.naming.InitialContext(properties);
		} catch (Exception e) {
			System.out.println("Unable to connect to WebLogic server at " + url);
			System.out.println("Please make sure that the server is running.");
			throw e;
		}
	}
}

